package com.wjk.cms.util.lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class LockUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public boolean lock(String key, int seconds) {
        Boolean result = redisTemplate.opsForValue().setIfAbsent(key, "1", seconds, TimeUnit.SECONDS);
        return result != null && result;
    }

    public boolean lock(String key) {
        return lock(key, 300);
    }

    public void unlock(String key) {
        redisTemplate.delete(key);
    }

}
